<template>
  <div class="navbar">
    <div class="left-side">
      <a-space>
        <img alt="logo" class="logo" :src="storeSideLogo" />

        <icon-menu-fold
          v-if="appStore.device === 'mobile'"
          style="font-size: 22px; cursor: pointer"
          @click="toggleDrawerMenu"
        />
      </a-space>
    </div>
    <ul class="right-side">
      <li>
        <a-button
          size="mini"
          style="margin-left: 20px"
          type="outline"
          @click="getIm"
        >
          点击登录客服
        </a-button>
      </li>
      <li>
        <div class="org-change">
          <a-space>
            <a-button size="large" class="btn">
              <template #default>{{
                userStore.userInfo.deptName
              }}</template></a-button
            >
            <a-button size="large" @click="handleChangeApp" class="btn">
              <template #icon v-if="userStore.userInfo.isMultipleShopStore">
                <icon-swap />
              </template>
              {{ userStore.userInfo.storeName }}</a-button
            >
            <a-button type="primary" @click="back">
              <!-- <template #icon>
              <icon-home />
            </template> -->
              <template #default>返回主页</template>
            </a-button>
          </a-space>
          <!-- <div class="org-name">{{ userStore.deptName }}</div> -->
        </div>
      </li>
      <li>
        <a-avatar
            :size="32"
            :style="{ marginRight: '8px', cursor: 'pointer' }"
          >
            <img alt="avatar" :src="avatar" v-if="avatar" />
            <icon-user v-else />
          </a-avatar>
        <!-- <a-dropdown trigger="click">
          <a-avatar
            :size="32"
            :style="{ marginRight: '8px', cursor: 'pointer' }"
          >
            <img alt="avatar" :src="avatar" v-if="avatar" />
            <icon-user v-else />
          </a-avatar>
          <template #content>
            <a-doption>
              <a-space @click="$router.push({ name: 'setting' })">
                <icon-settings />
                <span> 店铺设置 </span>
              </a-space>
            </a-doption>
            <a-doption>
              <a-space @click="handleLogout">
                <icon-export />
                <span> 退出 </span>
              </a-space>
            </a-doption>
          </template>
        </a-dropdown> -->
      </li>
    </ul>
    <change-app-select
      v-model:open="open"
      @changeApp="changeApp"
    ></change-app-select>
  </div>
</template>

<script lang="ts" setup>
  import { computed, ref, inject, onMounted } from 'vue';
  import { useDark, useToggle, useFullscreen } from '@vueuse/core';
  import { useAppStore, useUserStore } from '@/store';
  import useUser from '@/hooks/user';
  import changeAppSelect from './changeAppSelect.vue';
  import MessageBox from '../message-box/index.vue';
  import getAssetsImages from '@/utils/assetsImages';
  import { useTitle, useFavicon } from '@vueuse/core';
  import { changeSmallApp, getStoreInfo } from '@/api/login';
  import { initSiteInfo } from '@/hooks/fetchBaseSite';
  import { getIMDetail } from '@/api/common';
  import { useRouter } from 'vue-router';
  const router = useRouter();
  const storeSideLogo = ref<any>(
    localStorage.getItem('seller_logo') || getAssetsImages('logo.png')
  );
  const appStore = useAppStore();
  const userStore = useUserStore();
  const { logout } = useUser();
  import store from '@/utils/storage';
  import { Message } from '@arco-design/web-vue';
  const open = ref(false);
  const { isFullscreen, toggle: toggleFullScreen } = useFullscreen();

  const avatar = computed(() => {
    return userStore.userInfo.storeLogo;
  });
  const theme = computed(() => {
    return appStore.theme;
  });
  // const isDark = useDark({
  //   selector: 'body',
  //   attribute: 'arco-theme',
  //   valueDark: 'dark',
  //   valueLight: 'light',
  //   storageKey: 'arco-theme',
  //   onChanged(dark: boolean) {
  //     // overridden default behavior
  //     appStore.toggleTheme(dark);
  //   },
  // });
  // const toggleTheme = useToggle(isDark);
  // const handleToggleTheme = () => {
  //   toggleTheme();
  // };
  function handleChangeApp() {
    if (
      userStore.userInfo.isMultipleShopStore ||
      !userStore.userInfo.storeName
    ) {
      open.value = true;
    }
  }
  async function changeApp(item) {
    changeSmallApp(item).then(async () => {
      const userStore1 = useUserStore();
      const storeInfo = await getStoreInfo();
      userStore1.userInfo = storeInfo.data.result;
      router.push('/').then(() => {
        window.location.reload();
      });
    });
  }
  function isHttp(url) {
    return url.indexOf('http://') !== -1 || url.indexOf('https://') !== -1;
  }
  function back() {
    userStore.getTongYiSystemUrl().then((url) => {
      if (!isHttp(url)) {
        Message.error('未获取到有效地址, 请联系管理员');
        return;
      }
      window.location.replace(url);
    });
  }
  const setVisible = () => {
    appStore.updateSettings({ globalSettings: true });
  };
  const refBtn = ref();

  const setPopoverVisible = () => {
    const event = new MouseEvent('click', {
      view: window,
      bubbles: true,
      cancelable: true,
    });
    refBtn.value.dispatchEvent(event);
  };
  const handleLogout = () => {
    logout();
  };

  const toggleDrawerMenu: any = inject('toggleDrawerMenu');
  const accessToken = ref(store.getAccessToken());
  // 初始化方法
  const init = () => {
    storeSideLogo.value = localStorage.getItem('seller_logo');
    window.document.title =
      localStorage.getItem('seller_site_name') + ' - 商家后台';
    // window.document.title = '商家后台';
    const icon = useFavicon();
    const sellerIconImg = localStorage.getItem('seller_icon');
    icon.value = sellerIconImg;
    //动态获取icon
    let link =
      document.querySelector("link[rel*='icon']") ||
      (document.createElement('link') as any);
    link.type = 'image/x-icon';
    link.href = localStorage.getItem('sellerIconImg');
    link.rel = 'shortcut icon';
    document.getElementsByTagName('head')[0].appendChild(link);
  };
  async function getIm() {
    getIMDetailMethods();
  }
  // 获取im信息
  async function getIMDetailMethods() {
    const res = await getIMDetail();
    if (res.data.success) {
      window.open(`${res.data.result}?token=${accessToken.value}`);
    }
  }
  async function getUser() {
    const userStore1 = useUserStore();
    const storeInfo = await getStoreInfo();
    userStore1.userInfo = storeInfo.data.result;
  }
  onMounted(async () => {
    await initSiteInfo();
    init();
    getUser();
  });
</script>

<style scoped lang="less">
  .logo {
    max-width: 100px;
    max-height: 50px;
  }
  .navbar {
    display: flex;
    justify-content: space-between;
    height: 100%;
    background-color: var(--color-bg-2);
    border-bottom: 1px solid var(--color-border);
  }

  .left-side {
    display: flex;
    align-items: center;
    padding-left: 20px;
  }

  .right-side {
    display: flex;
    padding-right: 20px;
    list-style: none;
    :deep(.locale-select) {
      border-radius: 20px;
    }
    li {
      display: flex;
      align-items: center;
      padding: 0 10px;
    }

    a {
      color: var(--color-text-1);
      text-decoration: none;
    }
    .nav-btn {
      border-color: rgb(var(--gray-2));
      color: rgb(var(--gray-8));
      font-size: 16px;
    }
    .trigger-btn,
    .ref-btn {
      position: absolute;
      bottom: 14px;
    }
    .trigger-btn {
      margin-left: 14px;
    }
  }
  :deep(.arco-avatar-trigger-icon-button) {
    width: 32px;
    height: 32px;
    line-height: 32px;
    background-color: #e8f3ff;
    .arco-icon-camera {
      margin-top: 8px;
      color: rgb(var(--arcoblue-6));
      font-size: 14px;
    }
  }
</style>

<style lang="less">
  .message-popover {
    .arco-popover-content {
      margin-top: 0;
    }
  }
</style>
